<template>
  <div class="app-container" v-if="!blNo">
    <div class="query-wrapper" model="queryParams" style="margin-bottom: 10px;">
        <el-select v-model="queryParams.vesselName" filterable placeholder="Vessel" style="width:180px"
          @change="selectVessel">
          <el-option :key="item.vesselName" :label="item.vesselName" :value="item.vesselName" v-for="item in vessels">
          </el-option>
        </el-select>
        &nbsp;&nbsp;
        <el-select v-model="queryParams.voyageNo" filterable placeholder="Voyage" style="width:100px">
          <el-option :key="item.voyageNo" :label="item.voyageNo" :value="item.voyageNo" v-for="item in voyages">
          </el-option>
        </el-select>
        &nbsp;&nbsp; 
        <el-select v-model="queryParams.blType" filterable placeholder="B/L Type" style="width:160px;margin-right: 20px;">
          <el-option :key="item" :label="item" :value="index" v-for="(item,index) in blTypes">
          </el-option>
        </el-select>
        <span>&nbsp;&nbsp;</span>
        <el-button type="primary" icon="search" @click="search">{{ $t("ship.button.search") }}</el-button>
        <SearchReset :query-params="queryParams" @reset="resetQuery"></SearchReset>
        <!-- <span>&nbsp;&nbsp;</span>
        <el-button type="primary" @click="addClickEvent" v-hasPermi="['billOfLading:add']">
          {{ $t("ship.button.plus") }}
        </el-button> -->
      </div> 

    <el-table stripe :border="true" ref="tableRef" class="daf-table" :data="listData" style="width: 100%"
      @sort-change="handleSortChange" :show-overflow-tooltip="true" :cell-style ="{textAlign:'center'}" >
      <el-table-column prop="blNo" label="B/L No." L width="150" />
      <el-table-column prop="blType" label="B/L Type" width="120">
        <template #default="scope">
          {{ blTypes[scope.row.blType] }}
        </template>
      </el-table-column>
      <el-table-column prop="blStatus" label="B/L status" width="100" />
      <el-table-column prop="createBy" label="Created By" width="100" />
      <el-table-column prop="vesselName" label="Ocean Vessel" width="150" />
      <el-table-column prop="voyageNo" label="Voyage No." width="100" />
      <el-table-column prop="flag" label="Flag" width="100" />
      <el-table-column prop="pol" label="Port of Loading" width="150" />
      <el-table-column prop="pod" label="Port of Discharge" width="150" />
      <el-table-column prop="transhipment" label="For Transhipment to" width="150" />
      <el-table-column prop="marks" label="Mark and Numbers" width="150" />
      <el-table-column prop="totalUnits" label="No.& Kind of package" width="150" />
      <el-table-column prop="goodsDesc" label="Description of Goods" width="150" />
      <el-table-column prop="totalWeight" label="Gross weight" width="150" />
      <el-table-column prop="totalVolume" label="Measurement" width="150" />
      <el-table-column prop="freightPrepaid" label="Freight Prepaid at" width="150" />
      <el-table-column prop="issueDate" label="Date of Issue" width="150" />
      <el-table-column prop="originalBlNo" label="No. of Original B(s)/ L" width="150" />
      <el-table-column prop="freightPayable" label="Freight Payable at" width="150" />
      <el-table-column prop="arrangeDateAt" label="Date at" width="100" />
      <el-table-column prop="arrangeDate" label="Date" width="100" />
      <el-table-column prop="arrangeBy" label="BY" width="100" />
      <el-table-column prop="createTime" label="Final Destination" width="150" />
      <el-table-column label="Operation"  width="160" fixed="right">
        <template #default="scope">
          <span class="btn-primary" v-hasPermi="['issueBL:edit']" @click="editClickEvent(scope.row)">{{ $t("ship.button.edit") }}</span>&nbsp;&nbsp;
          <span class="btn-primary" v-hasPermi="['issueBL:edit']" @click="removeClickEvent(scope.row.id)">{{ $t("ship.button.remove") }}</span>
          &nbsp;&nbsp;
          <span class="btn-primary" v-hasPermi="['issueBL:export']" @click="handleExport(scope.row)">{{ $t("ship.button.export") }}</span>

          <!-- <el-dropdown placement="bottom-start">
            <span class="btn-primary" style="line-height: 24px;font-size: 12px;">
              Print<el-icon class="el-icon--right" size="14px" style="vertical-align: middle;"><arrow-down /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item fixed="right" @click="handleExport(scope.row,0)">OBL</el-dropdown-item>
                <el-dropdown-item fixed="right" @click="handleExport(scope.row,1)"> TELEX </el-dropdown-item>
                <el-dropdown-item fixed="right" @click="handleExport(scope.row,2)"> SEAWAY BILL</el-dropdown-item>
                <el-dropdown-item fixed="right" @click="handleExport(scope.row,3)"> MEMO BILL</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown> -->
          &nbsp;&nbsp;
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page="queryParams.pageNum" :limit="queryParams.pageSize"
      @pagination="pageQuery" style="float: right" />
  </div>

  <!---增加部分-->
  <div class="add-container" v-else>
    <el-form :model="formParam" :rules="rules" ref="custForm">
      <h2 style="text-align: center">BILL OF LADING</h2>
      <table>
        <tbody>
          <tr>
            <td valign="top" colSpan="6">
              <div class="title">Shipper / Exporter (complete name and address)</div>
              <el-form-item label="" prop="shipper">
                <el-input type="textarea" v-model="formParam.shipper" class="shipper" placeholder="" rows="5" />
              </el-form-item>

            </td>
            <td width="50%" valign="top" rowSpan="4" colSpan="2">
              <div class="title">BL No. <br /> <b style="line-height: 40px;">
                  &nbsp;&nbsp;&nbsp;&nbsp;{{formParam.blNo}}</b></div>
                <!--  <el-form-item label="" prop="blNo">
             <el-select v-model="formParam.blNo" @change="selectblNo" clearable filterable>
                <el-option v-for="item in blNos" :key="item" :value="item" :label="item" />
              </el-select>

              </el-form-item> -->
              <br />
              <div style="padding: 10px">
                IN ACCEPTANCE THIS BILL OF LADING, the shipper, owner, and consignee of the goods, and the holder of
                this Bill of
                Lading, expressly accept and agree to all its stipulations and conditions, whether written, stamped or
                printed, as
                fully as if signed by such shipper.owner, consignee and or holder. No agent is authorized to waive any
                of the
                provisions of the within clauses. Received from the shipper herein named the goods or packages in
                apparent good
                order and condition unless otherwise indicated in this bill of lading. This bill of lading is a receipt
                only for
                the number of packages shown herein. Weight measurements, marks and numbers, quality, quantity, contents
                and value
                shown above are furnished by the Merchant and have not been checked and are to be considered unknown
                unless
                expressly acknowledged and agreed. The signing of this bill of lading is not considered as such
                acknowledgement or
                agreement.Full freight and charge are payable as per agreement, but always deemed earned latest on
                signing of the
                bill of lading, without discount or refund, ship and/or goods lost or not. IN WITNESS WHEREOF, the
                Master or agent
                of the said ship has signed the number of original Bill (s) of Lading stated below, all of this tenor
                and date,
                ONE of which being accomplished, the others to stand void.
              </div>
            </td>
          </tr>
          <tr>
            <td valign="top" colSpan="6">
              <div class="title">Consignee (complete name and address)</div>
              <el-form-item label="" prop="consignee">
                <el-input type="textarea" v-model="formParam.consignee" class="consignee" placeholder=""
                  rows="5" />
              </el-form-item>
            </td>
          </tr>
          <tr>
            <td valign="top" colSpan="6">
              <div class="title">Notify party (complete name and address)</div>
              <el-form-item label="" prop="notifyParty">
                <el-input type="textarea" v-model="formParam.notifyParty" class="notifyParty" placeholder=""
                  rows="5" />
              </el-form-item>
            </td>
          </tr>
          <tr>
            <td valign="top" colSpan="3">
              <div class="title">Local Vessel</div>
              <el-form-item label="" prop="localVessel">
                <el-input v-model="formParam.localVessel" class="localVessel" placeholder="Local Vessel" />
              </el-form-item>
            </td>
            <td valign="top" colSpan="3">
              <div class="title">From</div>
              <el-form-item label="" prop="localFrom">
                <el-input v-model="formParam.localFrom" class="from" placeholder="From" />
              </el-form-item>
            </td>
          </tr>
          <tr>
            <td valign="top" colSpan="2">
              <div class="title">Ocean Vessel</div>
              <el-form-item label="" prop="vesselName">
                <el-input v-model="formParam.vesselName" class="vesselName" placeholder="Ocean Vessel" />
              </el-form-item>
            </td>
            <td valign="top" colSpan="2">
              <div class="title">Voyage No.</div>
              <el-form-item label="" prop="voyageNo">
                <el-input v-model="formParam.voyageNo" class="voyageNo" placeholder="voyageNo" />
              </el-form-item>
            </td>
            <td valign="top" colSpan="2">
              <div class="title">Flag</div>
              <el-form-item label="" prop="flag">
                <el-input v-model="formParam.flag" class="flag" placeholder="Flag" />
              </el-form-item>
            </td>
            <td valign="top" colSpan="2">
              <div class="title">Final Destination (for the shipper's reference only)</div>
              <el-form-item label="" prop="destination">
                <el-input v-model="formParam.destination" class="destination" placeholder="Final Destination" />
              </el-form-item>
            </td>
          </tr>
          <tr>
            <td valign="top" colSpan="3">
              <div class="title">Port of Loading</div>
              <el-form-item label="" prop="pol">
                <el-input v-model="formParam.pol" class="destination" placeholder="POL" />
              </el-form-item>
              <!---
              <el-select v-model="formParam.pol" filterable placeholder="choose port" clearable @change="polChange" style="width: 320px">
                <el-option :key="item.countryName" :label="item.countryName" :value="item.countryName" v-for="item in countrys">
                </el-option>
              </el-select>--->
            </td>
            <td valign="top" colSpan="3">
              <div class="title">Port of Discharge</div>
              <el-form-item label="" prop="pod">
                <el-input v-model="formParam.pod" class="destination" placeholder="POD" />
              </el-form-item>
            </td>
            <td valign="top" colSpan="2"> 
              <div class="title">For Transhipment to</div>
              <el-form-item label="" prop="transhipment">
                <el-input v-model="formParam.transhipment" class="transhipment" placeholder="" />
              </el-form-item>
            </td>
          </tr>
        </tbody>
      </table>
      <h2 style="text-align: center">PARTICULAR FURNISHED BY SHIPPER</h2>
      <table width="100%">
        <tbody>
          <tr>
            <td valign="top" style="min-width:200px;width:200px">
              <div class="title">Mark and Numbers</div>
              <el-form-item label="" prop="marks" style="width:240px">
                <el-input v-model="formParam.marks" class="marks" placeholder="" />
              </el-form-item>
            </td>
            <td valign="top" style="min-width:200px;width:200px">
              <div class="title">No.& Kind of package</div>
              <el-form-item label="" prop="totalUnits">
                <div class="input-with-unit">
                  <el-input   v-model="formParam.totalUnits" class="totalUnits custom-textarea" placeholder="" />
                   <span class="unit">{{ formParam.unit }}</span>
                </div>
                <!-- <el-input-number v-model="formParam.totalUnits" class="totalUnits" placeholder="totalUnits" />{{
                formParam.unit }} -->
              </el-form-item>
            </td>
            <td valign="top" style="min-width:300px" >
              <div class="title">Description of Goods</div>
              <el-form-item label="" prop="goodsDesc">
                <el-input  type="textarea" v-model="formParam.goodsDesc" class="goodsDesc" />
              </el-form-item>
            </td>
            <td valign="top" style="min-width:150px;width:150px">
              <div class="title">Gross weight</div>
              <el-form-item label="" prop="totalWeight">
                <!-- <el-input-number v-model="formParam.totalWeight" class="totalWeight"   /> -->
                <div class="input-with-unit">
                <el-input  type="textarea" v-model="formParam.totalWeight" class="totalWeight custom-textarea" placeholder="" /> 
                     <span class="unit">KGS</span>
                </div>
              </el-form-item>
            </td>
            <td valign="top" style="min-width:150px;width:150px">
              <div class="title">Measurement</div>
              <el-form-item label="" prop="totalVolume">

                <div class="input-with-unit">
                  <el-input  type="textarea" v-model="formParam.totalVolume" class="totalVolume custom-textarea" placeholder="" ></el-input>
                  <span class="unit">CBM</span>
                </div>
              </el-form-item>
            </td>
          </tr>
          <tr>
            <td valign="top"colSpan="2" >
              Total Number of Package or Units (in words) &nbsp;&nbsp; &nbsp;&nbsp;
            </td>
            <td valign="top" colSpan="2" style="font-size:18px;font-weight:bold">
               <div style="  display: flex;
                align-items: center;
                height: 40px;
                border: 1px solid #dcdfe6;
                border-radius: 4px;
                padding: 8px;
                font-size: 14px;
                color: #606266;
                background-color: #fff;
                transition: border-color 0.3s;">SAY:TOTAL {{numberToWords(formParam.totalUnits)}} {{formParam.unit}}(s) ONLY</div>
            </td>
            <td valign="top">
            </td>
          </tr>
          <tr>
            <td  valign="top" >
              Remark
            </td>
            <td colSpan="3">
              <el-input v-model="formParam.remark" type="textarea"  rows="3"/>
            </td>
          </tr>
        </tbody>
      </table>

      <h2 style="text-align: center">AS ARRANGED</h2>
      <el-row class="bt">
        <el-col :span="7" class="br mt pt">
          Freight Prepaid at <el-input style="width: 60%;" v-model="formParam.freightPrepaid" class="freightPrepaid"
            placeholder="" />
        </el-col>
        <el-col :span="7" class="br pt" style="display: flex;padding:10px 0 0 10px">
         <span style="line-height: 32px;margin-right: 10px; ">Date of Issue </span>
         <el-form-item  label="" prop="issueDate">
          <el-date-picker v-model="formParam.issueDate" value-format="YYYY-MM-DD" 
              placeholder="" />
          </el-form-item>

        </el-col>
        <el-col :span="9" style="display: flex;padding:10px" class="pt">
          <div style="white-space: nowrap;">
            No. of Original B(s)/ L 
          </div>
            
          <!-- <el-input-number style="width: 220px" v-model="formParam.originalBlNo"
            class="originalBLNo" placeholder="" /> -->
            <el-input style="margin-left: 10px;"  v-model="formParam.originalBlNo" class="originalBlNo pb" placeholder="" />
          </el-col>
      </el-row>
      <el-row style="margin-top: 10px;" class="bt mt ">
        <el-col :span="7" class="br pt">
          Freight Payable at
          <el-input style="width: 60%;" v-model="formParam.freightPayable" class="freightPayabled" />
        </el-col>
        <el-col :offset="0" :span="7" class="br pt" style="padding:10 0 0 10px">
          <div class="" style=" padding: 0 0 8px 10px; line-height: 25px;">
            LADEN ON BOARD in apparent good order and condition unless otherwise stated
          </div>
        </el-col>
        <el-col :span="9" style="display: flex;padding: 10px" class="pt ">
          <div style="white-space: nowrap;">
            Dated at:
          </div>
          <el-input style="margin-left: 102px;" type="textarea" v-model="formParam.arrangeDateAt" class="arrangeDateAt" placeholder="" />
          <!-- <el-date-picker style="margin-left: 102px;" v-model="formParam.arrangeDateAt" type="date"  value-format="YYYY-MM-DD"/> -->
        </el-col>
      </el-row>
      <el-row class="bt bb">
        <el-col :span="7" class="br"></el-col>
        <el-col :offset="0" :span="7" class="br pt pb" style="display: flex;padding: 10px">
          Date:<el-date-picker style="margin-left: 62px;" v-model="formParam.arrangeDate" type="date" value-format="YYYY-MM-DD"/>
        </el-col>
        <el-col :span="9" class="pt pb" style="display: flex;padding:  10px">
          BY:<el-input v-model="formParam.arrangeBy" class="originalBLNo" placeholder=""
            style="margin-left: 140px;" />
        </el-col>
      </el-row>
      <table width="100%">
        <tbody>
          <tr>
            <td valign="top"></td>
            <td valign="top" style="text-align: center" /> 
            <td valign="top"></td>
          </tr>
          <tr>
            <td valign="top"></td>
            <td valign="top" style="text-align: center">
              <!-- Date:<el-input v-model="formParam.Date" class="Date" type="date" placeholder="Date" style="width: 200px" /> -->
            </td>
            <td valign="top">
              <div class="title"></div>
              &nbsp;&nbsp; &nbsp; &nbsp;
            </td>
          </tr>
        </tbody>
      </table>
      <el-row>
        <el-button type="primary" style="margin-top: 10px;" onclick="this.nextSibling.click()">Appendix</el-button>
        <input type="file" id="upload-file" v-show="false" @change="uploadFile($event)" accept=".pdf" multiple />
        <div @mouseenter="mouseoverHandle(true)" @mouseleave="mouseoverHandle(false)" class="file-list">
          <div v-if="files.length > 0" style="display: flex; flex-direction: column; margin-left: 10px;">
            <template v-for="(file, index) in files" :key="index">
              <div style="display: flex; align-items: center; margin-bottom: 5px;">
                <a href="javascript:void(0)" @click="preViewPDF(file)">
                  {{ getFileName(file.name) }}
                </a>
                <el-icon style="margin-left: 10px; cursor: pointer;" @click.stop="deleteSingleFile(index,1)"><Delete /></el-icon>
              </div>
            </template>
          </div>
          <div v-if="formParam.appendixList" style="display: flex;justify-content: center;align-items: center;">
            <div v-for="(value,valueIndex) in formParam.appendixList" :key="valueIndex" style="margin-left: 10px;">
            <a href="javascript:void(0)" @click="preViewPDF(value)" >
              {{ getFileName(value) }}
            </a>
             <el-icon style="margin-left: 10px; cursor: pointer;vertical-align: middle;" @click.stop="deleteSingleFile(valueIndex,2,value)"><Delete /></el-icon>
            </div>
            
          </div>
        </div>
      </el-row>
      <!-- <iframe v-if="formParam.file || formParam.appendix" :src="pdfUrl || convertUrl(formParam.appendix)" width="100%" height="600px"></iframe> -->
      <el-row>
        <el-col :span="24">
          <div class="dialog-footer">
            <el-button @click="cancelForm">{{ $t("ship.button.cancel") }}</el-button> &nbsp; &nbsp;
            <el-button type="primary" @click="submitForm(0)">{{ $t("ship.button.submit") }}</el-button>&nbsp;&nbsp;
            <el-button type="primary" @click="submitForm(1)">{{ $t("ship.button.submission") }}</el-button>
          </div>
          <br /><br /><br />
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>
<script lang="ts" setup name="issueBL">
import Pdf from "pdf-vue3";
  import { ref, onMounted, reactive, computed } from "vue";
  import { ElNotification, ElMessageBox, ElMessage } from "element-plus";
  import { downloadFile } from "@/utils/downloadFile";
  import { useTableDrag } from '@/hooks/useHooks';
  import { convertDate } from "@/utils/date";
  import service from "@/utils/request";
  import {convertUrl} from "@/utils/tencentCos";

  const { tableRef } = useTableDrag();
  const route = useRoute();
  const router = useRouter();
  const custForm = ref(null); 
  let vessels = reactive([])
  let voyages = reactive([])
  const files = ref([]);
  const initForm = {
    id: null,
    blNo: null,
    blType: null,
    orignalBlNo: null,
    url: null,
    localVessel: null,
    localFrom: null,
    notifyParty: null,
    consignee: null,
    invoiceDate: null,
    shipper: null,
    flag: null,
    fixtureNo: null,
    freightDate: convertDate(new Date()),
    salesId: null,
    clientName: null,
    mobile: null,
    receiver: null,
    contact: null,
    vesselName: null,
    voyageNo: null,
    sailedOn: null,
    issueDate: null,
    transhipment: null,
    totalWeight: null,
    totalVolume: null,
    goodsDesc: null,
    totalUnits: null,
    unit: null,
    marks: null,
    pol: null,
    pod: null,
    remark:null,
    bookingNo: null,
    originalBlNo: null,
    units: null,
    destination: null,
    freightPrepaid: null,
    freightPayable: null,
    arrangeDateAt: null,
    arrangeDate: null,
    arrangeBy: null,
    appendix:null,
    appendixList:null,
    file:null
  };

  let blNo = route.query?.blNo;
  const formParam = reactive(Object.assign({}, initForm));

  const total = ref(0); 

  const rules = ref({
    blNo: [{ required: true, message: "B/L No. can't be blank", trigger: "blur" }],
    shipper: [{ required: true, message: "Shipper can't be blank", trigger: "blur" }],
    consignee: [{ required: true, message: "Consignee can't be blank", trigger: "blur" }],
    notifyParty: [{ required: true, message: "Notify Party can't be blank", trigger: "blur" }],
    vesselName: [{ required: true, message: "Vessel Name can't be blank", trigger: "blur" }],
    voyageNo: [{ required: true, message: "Voyage can't be blank", trigger: "blur" }],
    pol: [{ required: true, message: "pol can't be blank", trigger: "blur" }],
    pod: [{ required: true, message: "pod can't be blank", trigger: "blur" }],
    issueDate: [{ required: true, message: "Issue Date can't be blank", trigger: "change" }],
  });

  const queryParams = reactive({
    pageNum: 1,
    pageSize: 20,
    vesselName: null,
    voyageNo: null,
    blNo: null,
    blType: null,
    orderByColumn: undefined,
    isAsc: undefined
  });

  const blTypes = ['Original B/L','Telex Release B/L','Memo B/L','Seaway B/L'];
  let blNos = reactive([]);
  const listData = ref([]);
  const refreshTable = async () => {
    window.localStorage.setItem("Issue_voyageCode",queryParams.voyageNo);
    window.localStorage.setItem("Issue_vesselName",queryParams.vesselName);

    if (!blNo) {
      let result = await service.get("/shipping/billOfLading/getTable", { params: queryParams });
      if (result) {
        listData.value = result.data;
        total.value = result.total;
      }
    }
  };
  const resetQuery = (data) => {
    Object.assign(queryParams, data)
    listData.value = []
    total.value = 0
  }
  const selectVessel = value => {
    voyages = (vessels.find(item => item.vesselName == value) || { schedules: [] }).schedules;
  };

  const portPod = ref("");
  const portPol = ref("");
  const parentId = ref();
  const selectblNo = async () => {
    formParam.blNo = blNo
    if (formParam.blNo && formParam.blNo.length > 0) {
      let params = reactive({ blNo: formParam.blNo });
      let result = await service.get("/shipping/billOfLading/getByBlNo", { params: params });
      if (result) {
        portPod.value = result.data.pod.split(',')[0]
        portPol.value = result.data.pol.split(',')[0]
        parentId.value=formParam.id
        Object.keys(result.data).forEach(k => {
          if(k!='appendixList'&&k!='id'&&k!='atd'){
            formParam[k] = result.data[k]
          }
          if(k=='appendixList'&&result.data[k]!=null){
            formParam.appendixList = result.data[k]
            formParam.files = result.data[k]
          }
         
          if(k=='id'){
            formParam.id = null
          }
        });
      }
    } else {
      // Object.keys(formParam).forEach(key => {
      //   formParam[key] = ""
      // })
    }

  };

  let isAdd = false;
   
  if(blNo){
    selectblNo() 
  }
  // watch(() => showForm,
  //   () => {
  //     if (showForm == '1') {
  //       Object.keys(initForm).forEach(key => {
  //         formParam[key] = initForm[key]
  //       })
  //     } else {
  //       if (showForm == 2) {          
  //         let recordData = JSON.parse(localStorage.getItem('BILL_INFO')) 
  //         console.log( recordData )
  //         Object.keys(recordData).forEach(key => {
  //           formParam[key] = recordData[key]
  //         })          
          
  //       }
  //     }
  //   },
  //   { immediate: true }
  // )
  const cancelForm = () => { 
    //history.back() 
    window.localStorage.setItem("callback","1")
    history.back() 
    isAdd = false
  }
  const addClickEvent = () => {
    isAdd = true;
    Object.assign(formParam, initForm);
    router.push({ path: "/billOfLading/issueBL", query: { showForm: 1 } });
  };
  const editClickEvent = (row:any) => {
    isAdd = false;
    Object.keys(row).forEach(k => (formParam[k] = row[k]));
    //localStorage.setItem('BILL_INFO', JSON.stringify(formParam))
    router.push({ path: "/billOfLading/issueBL", query: { blNo: row.blNo }});
  };
  const resetForm = () => {
    // @ts-ignore
    custForm.value.resetFields();
    portPol.value = "";
    portPod.value = "";
  };


  const submitForm = (status: any) => {
    // @ts-ignore
    if(status) {
      custForm.value.validate(async valid => {
        if (!valid) {
          // @ts-ignore
          ElNotification.warning({ title: "Prompt information", message: "verification not success！", position: "bottom-right" });
          return;
        }
      //  const formData = new FormData();
      
      // // 添加表单数据
      // Object.keys(formParam).forEach(key => {
      //   if (key !== 'file' && key !== 'appendix') {
      //     formData.append(key, formParam[key]);
      //   }
      // });
      
      // // 添加多个文件
      // files.value.forEach(file => {
      //   formData.append('file', file.file);
      // });
        const formData = new FormData()
        for (const [k, n] of Object.entries(formParam)) {
            if (n&&k !== 'file') {
                formData.append(k, n)
            }
        }
        formData.append('status', status)
        files.value.forEach(file => {
          formData.append('file', file.file);
        });
        await service.post("shipping/billOfLading/update", formData);
        // @ts-ignore
        ElNotification.success({ title: "Prompt information", message: "save successful!", position: "bottom-right" });
        cancelForm()
      });
    } else {
      const formData = new FormData()
      for (const [k, n] of Object.entries(formParam)) {
            if (n&&k !== 'file') {
                formData.append(k, n)
            }
        }
        formData.append('status', status)
        files.value.forEach(file => {
          formData.append('file', file.file);
        });
        service.post("shipping/billOfLading/update", formData);
        // @ts-ignore
        ElNotification.success({ title: "Prompt information", message: "save successful!", position: "bottom-right" });
        cancelForm()
    }
  };

  const pageQuery = async e => {
    queryParams.pageNum = e.page;
    queryParams.pageSize = e.limit;
    refreshTable();
  };

  const search = () => {
    if (queryParams.voyageNo == null) {
      ElMessage.warning("Please select Vessel and voyage to query!");
      return
    }
    refreshTable();
  };

  const handleSortChange = async (column: any) => {
    queryParams.orderByColumn = column.prop;
    queryParams.isAsc = column.order; //动态取值排序顺序
    refreshTable();
  };

  const removeClickEvent = id => {
    ElMessageBox.confirm("Confirm to Remove the data？", "Confirmation Information", {
      type: "warning",
      confirmButtonText: "Confirm",
      cancelButtonText: "Cancel"
    }).then(async () => {
      await service.delete(`shipping/billOfLading/${id}`);
      refreshTable();
      // @ts-ignore
      ElNotification.success({ title: "Prompt information", message: "Delete successfully!", position: "bottom-right" });
    });
  }

  function handleExport(row: any) {
    //row.blType = type
    downloadFile("/shipping/billOfLading/export", row, `${new Date().getTime()}billOfLading.pdf`);
  }
  function numberToWords(num:number) {
    const units = ['', 'ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX', 'SEVEN', 'EIGHT', 'NINE', 'TEN',
      'ELEVEN', 'TWELVE', 'THIRTEEN', 'FOURTEEN', 'FIFTEEN', 'SIXTEEN',
      'SEVENTEEN', 'EIGHTEEN', 'NINETEEN'];

    const tens = ['', '', 'TWENTY', 'THIRTY', 'FORTY', 'FIFTY', 'SIXTY', 'SEVENTY', 'EIGHTY', 'NINETY'];

    const scales = ['', 'THOUSAND', 'MILLION', 'BILLION'];

    if (num === 0) {
      return 'ZERO';
    }

    let result = '';
    let scaleIndex = 0;

    while (num > 0) {
      let part = num % 1000;
      let partWords = '';

      if (part >= 100) {
        partWords += units[Math.floor(part / 100)] + ' HUNDRED';
        part %= 100;
      }

      if (part >= 20) {
        partWords += ' ' + tens[Math.floor(part / 10)];
        part %= 10;
      }

      if (part > 0) {
        if (partWords.length > 0) {
          partWords += ' ' + units[part];
        } else {
          partWords += units[part];
        }
      }

      if (partWords.length > 0) {
        if (result.length > 0) {
          if (scaleIndex > 0 && result.indexOf(' ') === 0) {
            // 移除前一个数量级前的空格
            result = result.substr(1);
          }
          result = partWords + ' ' + scales[scaleIndex] + ' ' + result;
        } else {
          result = partWords;
        }
      }

      num = Math.floor(num / 1000);
      scaleIndex++;
    }

    return result.trim();
  }
  const pdfUrl = ref();
  const pdfKey = ref(Date.now());
  const preindex = ref(0);
  const isUploadPre = ref(true);
  const uploadFile = async (event) => {
  if (event.target == null || event.target.files.length === 0) {
    return;
  }
  // 处理新选择的文件
  const newFiles = Array.from(event.target.files);
  
  newFiles.forEach(file => {
    const reader = new FileReader();
    reader.readAsDataURL(file); // 读取文件为 Base64
    reader.onload = (e) => {
      const fileData = {
        name: file.name,
        file: file,
        pdfUrl: e.target.result
      };
      files.value.push(fileData);
      pdfKey.value = Date.now();
    };
  });
  
  // 清空input值，允许重复选择同一文件
  event.target.value = '';
};
  // 获取文件名称
  function getFileName(name) {
    if (name == null) {
      return name;
    }
    // 如果是url那么取最后的名字 如果不是直接返回
    if (name.lastIndexOf("/") > -1) {
      return name.slice(name.lastIndexOf("/") + 1);
    } else {
      return name;
    }
  }
 function preViewPDF(value: any) {
  console.log('[ value ] >', value)
    let url=value.pdfUrl?value.pdfUrl:convertUrl(value) 
    window.open(router.resolve({ path: '/pdfView/index', query: { pdfUrl: url} }).href, '_blank')
  }
  function downloadPDF(formParam: any) { 
    ElMessageBox.confirm("Confirm to Download the file？", "Download  Information", {
      type: "warning",
      confirmButtonText: "Confirm",
      cancelButtonText: "Cancel",
    }).then(async () => {
      if(formParam.file) { 
        const fileName = formParam.file.name;
        const fileUrl = URL.createObjectURL(formParam.file); // 创建 Blob URL 
        const a = document.createElement('a');
        a.href = fileUrl;
        a.download = fileName; // 保留原文件名
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(fileUrl); // 释放 URL
      } else {
        const newUrl = convertUrl(formParam.appendix);
        const a = document.createElement('a');
        a.href = newUrl;
        a.download = getFileName(newUrl);
        a.click();
      }

    });
  }
  // 下载单个文件
function downloadSingleFile(file) {
  const fileUrl = URL.createObjectURL(file.file);
  const a = document.createElement('a');
  a.href = fileUrl;
  a.download = file.name;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(fileUrl);
}

// 删除单个文件
  function deleteSingleFile(index,type,value) { 
  ElMessageBox.confirm("Confirm to Delete the file？", "Delete Information", {
    type: "warning",
    confirmButtonText: "Confirm",
    cancelButtonText: "Cancel",
  }).then(async() => {
    if(type == 1) {
      files.value.splice(index, 1);
    } else {
      await service["post"]("/shipping/billOfLading/deleteFile", { id: parentId.value, url: value });
      formParam.appendixList.splice(index,1)
    }
    ElNotification.success({ title: "Prompt information", message: "delete the File success!", position: "bottom-right" });
  });
}
  function deletePDF(formParam: any) {  
    ElMessageBox.confirm("Confirm to Delete the file？", "Delete  Information", {
      type: "warning",
      confirmButtonText: "Confirm",
      cancelButtonText: "Cancel",
    }).then(async () => {
        if(formParam.appendix) {
		   await service["post"]("/shipping/billOfLading/deleteFile", { id: formParam.id, url: formParam.appendix });
		   ElNotification.success({ title: "Prompt information", message: "delete the File success!", position: "bottom-right" });
       formParam.appendix = null;
      }else {
        formParam.file = null;      
      }

    });
  }
  const isDel = ref(false)
  //防抖函数
  const debounce = (fn, t) => {
    let delay = t || 300
    let timer
    return function () {
      let args = arguments
      if (timer) {
        clearTimeout(timer)
      }
      let callNow = !timer
      timer = setTimeout(() => {
        timer = null
      }, delay)
      if (callNow) fn.apply(this, args)
    }
  }
  const mouseoverHandle = debounce((status) => {
    isDel.value = status
  }, 500)

    if(window.localStorage.getItem("callback")=="1" && window.localStorage.getItem("Issue_voyageCode")){
        window.localStorage.setItem("callback","2")
        queryParams.voyageNo=window.localStorage.getItem("Issue_voyageCode");
        queryParams.vesselName=window.localStorage.getItem("Issue_vesselName");
    }

  onMounted(async () => {
    let result = await service.get("/shipping/cargoManifest/import");
    blNos = result.data;

    result = await service.get("/shipping/schedule/getAllSchedule");
    if (result) {
      vessels = result.data;
    }
    if(queryParams.vesselName){
         refreshTable();
         voyages = (vessels.find(item => item.vesselName == queryParams.vesselName) || { schedules: [] }).schedules;
    }
  });
</script>

<style lang="scss" scoped>
  .add-container {
    padding: 30px;
    background-color: #fafafa;
    height: 100%;
  }

  .title {
    padding: 10px 10px 10px 0;
  }

  .dialog-footer {
    margin: 60px auto 0;
    width: 100%;
    text-align: center;
  }

  .input-with-unit {
  position: relative;
  display: inline-block;
  width: 100%; /* 根据需求调整宽度 */
  /* 调整输入框内边距，避免文字被单位遮挡 */
  .custom-textarea :deep(.el-textarea__inner) {
    padding-right: 40px; 
    resize: vertical; /* 可选，允许垂直调整大小 */
  }
  
  /* 单位样式 */
  .unit {
    position: absolute;
    right: 12px;
    color: #888;
    font-size: 14px;
    pointer-events: none; /* 防止干扰输入 */
    background: white; /* 可选，避免与文本重叠 */
    padding-left: 4px; /* 背景衬托 */
  }
  
}

.file-list{
    padding:0 16px;
    display: flex;
    margin-top: 20px;
}
.br{
  border-right: 1px solid #000;
}
.bl{
  border-left: 1px solid #000;
}
.bb{
  border-bottom: 2px solid #000;
}
.bt{
  border-top: 1px solid #000;
}
.mt{
  margin-top: 0 !important;

}
.pt{
  padding-top: 10px;
}
.pb{
  padding-bottom: 10px;
}
.bn{
  border: none;
}
</style>